package com.david.fastmsg.filter;

import com.david.fastmsg.exception.RespException;
import com.david.fastmsg.utils.ResponseUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @author qzw
 * @date 2020/8/29
 */
@ControllerAdvice
public class ExpetionHandle {

    /**
     * 返回Validated错误
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Map<String, Object> handleBindException(BindException e) {
        BindingResult bindingResult = ((BindException)e).getBindingResult();
        StringBuilder errMsg = new StringBuilder();
        for (int i = 0 ; i < bindingResult.getFieldErrors().size() ; i++) {
            if(i > 0) {
                errMsg.append(",");
            }
            FieldError error = bindingResult.getFieldErrors().get(i);
            errMsg.append(error.getDefaultMessage());
        }
        return ResponseUtils.fail("1001", errMsg.toString());
    }

    @ExceptionHandler(RespException.class)
    @ResponseBody
    public Map<String, Object> handleRespException(RespException e) {
        return ResponseUtils.fail(e.getRespCode(), e.getRespMsg());
    }
}
